﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Helpers;
using MVCWeb.Models.ViewData;
using MVCWeb.Models;
using System.Threading;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.Sql;

namespace MVCWeb.Controllers
{
    //http://blogs.msdn.com/matt/archive/2008/09/09/sql-ce-3-5-with-linq-to-sql.aspx
    /// ConnectionPool connectionPool = new ConnectionPool(MyConnectionString);
    /// using(Northwind db = new Northwind(connectionPool.Connection)) 
    /// <summary>
    /// Manages open connections on a per-thread basis
    /// 
    /// </summary>
    public class ConnectionPool
    {
        private Dictionary<int, IDbConnection> threadConnectionMap;

        /// <summary>
        /// Gets the connection string.
        /// </summary>
        /// <value>The connection string.</value>
        public string ConnectionString
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a connection.
        /// </summary>
        /// <returns>An open connection</returns>
        public IDbConnection Connection
        {
            get
            {
                lock (threadConnectionMap)
                {
                    int threadId = Thread.CurrentThread.ManagedThreadId;

                    IDbConnection connection = null;
                    if (threadConnectionMap.ContainsKey(threadId))
                    {
                        connection = threadConnectionMap[threadId];
                    }
                    else
                    {
                        connection = new SqlConnection(ConnectionString);
                        connection.Open();
                        threadConnectionMap.Add(threadId, connection);
                    }

                    return connection;
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionPool"/> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        public ConnectionPool(string connectionString)
        {
            threadConnectionMap = new Dictionary<int, IDbConnection>();
            ConnectionString = connectionString;
        }
    }
}